<?php

namespace app\middleware;

use Shopwwi\LaravelCache\Cache;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

/**
 * 全局请求中间件
 */
class Access implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        $header = [
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Origin' => $request->header('origin', '*'),
            'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
            'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
        ];

        //判断是否是options请求
        if ($request->method() == 'OPTIONS') {
            return response('', 200, $header);
        }

        //今日请求量增加
        Cache::increment('request_pv_' . strtotime(date('Y-m-d 00:00:00')));
        //站点总请求量
        Cache::increment('request_pv_total');

        //继续执行，并得到一个响应
        $response = $next($request);

        // 给响应添加跨域相关的http头
        $response->withHeaders($header);

        $exception = $response->exception();
        if ($exception) {
            //存在异常
        }

        return $response;
    }
}
